<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slip-select-request="slipSelectRequest"
          :clear-type="clearType"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-match>
            <el-button :disabled="!canMatch" @click="hisMatch()"
              >处理
            </el-button>
          </template>
          <template v-slot:filter-cancel>
            <el-button :disabled="!canCancel" @click="hisCancel()"
              >关闭
            </el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :row-class-name="tableRowClassName"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('consumeOrder:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
      </table-container>
    </div>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      @reset="handleClose"
    >
      <!-- <ScanInputBox
        v-if="dialogInfo.row.operateType === 1"
        :query="scanInfo.query"
        :api="scanInfo.api"
        @callback="onCallBackScanData"
      /> -->
      <div class="scan-input-box">
        <el-input
          ref="codeInput"
          v-model="scanInfo.code"
          :clearable="true"
          style="width: 400px"
          placeholder="请输入编码"
          @input="(e) => (scanInfo.code = validSe(e))"
        >
          <template #prepend>编码</template>
        </el-input>
      </div>
    </page-dialog>

    <HisCharging
      v-if="hisChargingInfo.visible"
      v-model:showDialog="hisChargingInfo.visible"
      :queryParams="hisChargingInfo.queryParams"
      :query="hisChargingInfo.queryMap"
      :qty="hisChargingInfo.row.qty"
      @callback="hisChargingCallback"
    ></HisCharging>
    <HisRefund
      v-if="hisRefundInfo.visible"
      v-model:showDialog="hisRefundInfo.visible"
      :queryParams="hisRefundInfo.queryParams"
      :qty="hisRefundInfo.row.qty"
      @callback="hisRefundCallback"
    ></HisRefund>
    <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
  </div>
</template>

<script setup name="hisChargingInformation">
import ScanInputBox from './component/ScanInputBox'
import HisCharging from './component/HisCharging'
import HisRefund from './component/HisRefund'
import {
  getHisCustomizeListPage,
  hisStockLockMatch,
  hisStockLockSupplement,
  hisStockLockCancel,
  hisStockLockScan,
  hisExcel,
} from '@/api/his'
import {
  mappingHisSpdDeductConsumeConfirm,
  mappingHisSpdReturnDeductConfirm,
} from '@/api/mapping'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { computed } from 'vue'
const { proxy } = getCurrentInstance()
const route = useRoute()
const dialogInfo = ref({
  visible: false,
  title: '补录',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '补录',
      event: save,
      show: true,
    },
  ],
  row: {},
})

const scanInfo = ref({
  // api: hisStockLockScan,
  code: '',
  // query: {
  //   id: '',
  // },
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    isPagerByPrint: true, //打印是否分页
    isPagerByExport: false, //导出是否分页
    queryMap: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'match',
      show: proxy.$permission('hisChargingInformation:match'),
    },
    {
      type: 'slot',
      value: 'cancel',
      show: proxy.$permission('hisChargingInformation:cancel'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('hisChargingInformation:excel'),
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '处理',
        event: hisMatch,
        show: proxy.$permission('hisChargingInformation:match'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
      {
        label: '补录',
        event: hisSupplement,
        show: proxy.$permission('hisChargingInformation:supplement'),
        ifRender: function (row) {
          return row.status === 0 && (row.codeType === 2 || row.codeType === 3)
        },
      },
      {
        label: 'HIS扣费人工处理',
        event: hisCharging,
        show: proxy.$permission('hisChargingInformation:charging'),
        ifRender: function (row) {
          return row.isChange === 1 && row.operateType === 1
        },
      },
      {
        label: 'HIS退费人工处理',
        event: hisRefund,
        show: proxy.$permission('hisChargingInformation:refund'),
        ifRender: function (row) {
          return row.isChange === 1 && row.operateType === 2
        },
      },
      {
        label: '关闭',
        event: hisCancel,
        show: proxy.$permission('hisChargingInformation:cancel'),
        ifRender: function (row) {
          return row.status === 0 && (row.codeType === 2 || row.codeType === 3)
        },
      },
    ],
  },
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const excelPrint = ref({
  type: '',
  excel: {
    api: hisExcel, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const canMatch = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.status !== 0).length === 0
  )
})
const canCancel = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter(
      (row) => row.status !== 0 && (row.codeType !== 2 || row.codeType !== 3)
    ).length === 0
  )
})
const hisChargingInfo = ref({
  visible: false,
  row: {},
  queryParams: {
    stockAvailableCalcQtyGt: 0,
  },
  queryMap: {
    productId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    depotId: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: null,
    },
  },
})
const hisRefundInfo = ref({
  visible: false,
  row: {},
  queryParams: {
    id: '',
  },
  queryMap: {},
})
setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'his_spd_deal_status',
      show: false,
      hidden: true,
    },
    rid: {
      label: 'HISID',
      value: 'rid',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    execDeptId: {
      label: '执行科室ID',
      value: 'execDeptId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    execDeptName: {
      label: '执行科室',
      value: 'execDeptName',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    priceItemId: {
      label: '项目ID',
      value: 'priceItemId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    batchNo: {
      label: '批次号',
      value: 'batchNo',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    feeId: {
      label: '费用ID',
      value: 'feeId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    writeOffId: {
      label: '冲正费用ID',
      value: 'writeOffId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    orderDocName: {
      label: '开单医生',
      value: 'orderDocName',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    orderDocId: {
      label: '开单医生ID',
      value: 'orderDocId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    orderDeptName: {
      label: '开单科室',
      value: 'orderDeptName',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    orderDeptId: {
      label: '开单科室ID',
      value: 'orderDeptId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    patientId: {
      label: '病人ID',
      value: 'patientId',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    outPatientNo: {
      label: '门诊号住院号',
      value: 'outPatientNo',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    registerNo: {
      label: '挂号ID住院ID',
      value: 'registerNo',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    pullTime: {
      label: '同步时间',
      value: 'pullTime',
      componentType: 'dateTime',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    num: {
      label: 'HIS数量',
      value: 'num',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    receiveTime: {
      label: '接收时间',
      value: 'receiveTime',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
    clearingOfficer: {
        label: '结算人员',
        value: 'clearingOfficer',
        componentType: 'input',
        show: false,
        hidden: true,
        minWidth: '250px',
    },
    hisOrderNo: {
      label: 'HIS计费单号',
      value: 'hisOrderNo',
      componentType: 'input',
      show: false,
      hidden: true,
      minWidth: '250px',
    }
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
//扣费
function hisCharging(row) {
  hisChargingInfo.value.visible = true
  hisChargingInfo.value.row = row
  hisChargingInfo.value.queryMap.depotId.value = row.depotIds.toString()
  hisChargingInfo.value.queryMap.productId.value = row.productId
}
function hisChargingCallback(data, callback) {
  let qty = 0
  let params = []
  data.forEach((item) => {
    qty = proxy.$fn.accAdd(qty, item.qty || 0)
    params.push({
      hisId: hisChargingInfo.value.row.id,
      depotStockId: item.id,
      qty: item.qty,
    })
  })
  if (qty !== Math.abs(hisChargingInfo.value.row.qty)) {
    proxy.$message({
      showClose: true,
      message: '扣费数量和手动处理扣费数量必须保持一致，请修改',
      type: 'warning',
      duration: 3500,
    })
    return
  }

  mappingHisSpdDeductConsumeConfirm(params).then((res) => {
    if (res && res.success) {
      callback()
      getList()
    }
  })
}
//退费
function hisRefund(row) {
  hisRefundInfo.value.queryParams.id = row.id
  hisRefundInfo.value.row = row
  hisRefundInfo.value.visible = true
}
function hisRefundCallback(data, callback) {
  let qty = 0
  let params = []
  data.forEach((item) => {
    qty = proxy.$fn.accAdd(qty, item.qty || 0)
    params.push({
      hisId: hisRefundInfo.value.row.id,
      deductId: item.id,
      qty: item.qty,
    })
  })
  if (qty !== Math.abs(hisRefundInfo.value.row.qty)) {
    proxy.$message({
      showClose: true,
      message: '退费数量和手动处理退费数量必须保持一致，请修改',
      type: 'warning',
      duration: 3500,
    })
    return
  }
  mappingHisSpdReturnDeductConfirm(params).then((res) => {
    if (res && res.success) {
      callback()
      getList()
    }
  })
}
function hisMatch(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  hisStockLockMatch(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
function handleClose() {
  dialogInfo.value.visible = false
  dialogInfo.value.row = {}
  scanInfo.value.code = ''
  // scanInfo.value.query.id = ''
}
function hisSupplement(row = undefined) {
  dialogInfo.value.visible = true
  dialogInfo.value.row = row
  // scanInfo.value.query.id = row.id
}
// function onCallBackScanData(obj) {
//   let barcode = ''
//   if (obj.code) {
//     barcode = obj.code
//   } else if (obj.mainCode + obj.subCode) {
//     barcode = obj.mainCode + obj.subCode
//   }
//   let params = {
//     id: dialogInfo.value.row.id,
//     barcode: barcode,
//   }
//   proxy
//     .$confirm('是否用当前扫描进行补录', '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     })
//     .then(() => {
//       hisStockLockSupplement(params).then((res) => {
//         if (res && res.success) {
//           handleClose()
//           getList()
//         }
//       })
//     })
// }
function save() {
  if (!scanInfo.value.code) {
    proxy.$message({
      message: '请输入编码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let params = {
    id: dialogInfo.value.row.id,
    barcode: scanInfo.value.code,
  }
  proxy
    .$confirm('是否用当前输入编码进行补录', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      hisStockLockSupplement(params).then((res) => {
        if (res && res.success) {
          handleClose()
          getList()
        }
      })
    })
}
function hisCancel(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  hisStockLockCancel(ids).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
async function getList() {
  tableInfo.value.refresh = Math.random()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'HisSpdChargeDetailVOList-com.slip.spd.entity.vo.his.HisSpdChargeDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getHisCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
